<?php

declare(strict_types=1);

namespace App\Model;



use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\SessionInterface;

/**
 * @property int $id
 * @property string $path
 * @property string $component
 * @property string $redirect
 * @property string $name
 * @property string $title
 * @property string $icon
 * @property int $pid
 * @property int $level
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property string $deleted_at
 */
class Menu extends Model
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'menus';

    protected array $appends = ['meta', 'label', 'value'];

    protected array $hidden = ['always_show'];

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'path', 'component', 'redirect', 'name', 'title', 'icon', 'pid', 'level', 'created_at', 'updated_at', 'deleted_at'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'pid' => 'integer', 'level' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    public function childrenOne()
    {
        $role_id = ApplicationContext::getContainer()->get(SessionInterface::class)->get('admin_user')->role_id;
        if($role_id == 1){

            return $this->hasMany(get_class($this), 'pid', 'id');
        }else{

            return $this->hasMany(get_class($this), 'pid', 'id')->whereIn('id', RoleMenu::where('role_id', $role_id)->orderBy('menu')->pluck('menu'));
        }
    }
    public function children()
    {
        return $this->childrenOne()->with('children');
    }

    public function getMetaAttribute(): array
    {
        return [
            'title' => $this->title,
            'icon' => $this->icon
        ];
    }

    protected function getLabelAttribute(): string
    {
        return $this->title;
    }
    protected function getValueAttribute(): int
    {
        return $this->id;
    }
}
